package com.audaque.encoding.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.audaque.encoding.common.Page;
import com.audaque.encoding.mapper.EncodingHistoryMapper;
import com.audaque.encoding.model.EncodingHistory;
import com.audaque.encoding.model.EncodingLog;
import com.audaque.encoding.service.IEncodingService;
import com.audaque.encoding.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>编码接口</p>
 *
 * @author 谭黄
 * @since 2024/3/15
 */
@Service
@Slf4j
public class EncodingServiceImpl implements IEncodingService {

    @Autowired
    private EncodingHistoryMapper encodingHistoryMapper;


    @Override
    public Page<EncodingHistory> page(Page page) {
        Long size = page.getSize();
        Long total  = encodingHistoryMapper.pageCount();
        Long pages = (total + size - 1) / size;
        page.setTotal(total);
        page.setPages(pages);
        Long offset = (page.getCurrent() - 1) * size;
        Long limit=size;
        List<EncodingHistory> data=encodingHistoryMapper.page(offset,limit);
        page.setRecords(data);
        return page;
    }

    @Override
    public List<EncodingLog> selectEncodingLog(String fileId) {
        return encodingHistoryMapper.selectEncodingLog(fileId);
    }

    // 批量插入的大小阈值，可以根据实际情况调整
    private static final int BATCH_SIZE = 500;

    @Override
    public int insertEncodingLog(EncodingLog log) {
        return encodingHistoryMapper.insertEncodingLog(log);
    }

    @Override
    public int insertEncodingHistory(EncodingHistory eh) {
        return encodingHistoryMapper.insert(eh);
    }


    @Override
    public void saveEncoding(List<byte[]> res,String fileName) {
//        EncodingHistory eh = new EncodingHistory();
//        eh.setId(1L);
//        eh.setCreateTime(LocalDateTime.now());
//        eh.setStatus("abc");
//        eh.setRemark("dsc");
//        eh.setUser("admin");
//        encodingHistoryMapper.insert(eh);
        try {
            String name=fileName.substring(0,  fileName.lastIndexOf("."));
            String tableName=PinyinUtil.getPinyin(ExcelUtil.replace(name),"")+ "_"+DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
            log.info("07 动态表名： " + tableName);
            byte[] merge = ExcelUtil.merge(res);
            Map<String, String> stringStringMap = ExcelUtil.excel2TableColumn(merge);
            String createSql = ExcelUtil.createTableSql(tableName, stringStringMap);
            log.info("07 建表语句: \n" + createSql);
            log.info("07 执行drop语句和建表语句");
            encodingHistoryMapper.dropTableIfExists(tableName);
            encodingHistoryMapper.createTable(createSql);
            List<List<String>> list = ExcelUtil.excel2RowData(merge);
            fixListLength(list,stringStringMap.size());

            int totalSize = list.size();
            int batchCount = (totalSize + BATCH_SIZE - 1) / BATCH_SIZE;
            log.info("07 执行批量插入语句");
            for (int i = 0; i < batchCount; i++) {
                int fromIndex = i * BATCH_SIZE;
                int toIndex = Math.min((i + 1) * BATCH_SIZE, totalSize);
                List<List<String>> batchList = list.subList(fromIndex, toIndex);
                encodingHistoryMapper.batchInsertDynamic(tableName,new ArrayList<>(stringStringMap.keySet()),batchList);
                log.info("批次" + (i + 1) + "插入：" + batchList.size() + "条数据");
            }
        }catch (Exception e){
           throw new RuntimeException(e);
        }
    }


    /**
     * 补充数据行,避免数据行长度不一致
     * @param lists
     * @param num
     */
    private static void fixListLength(List<List<String>> lists, int num) {
        for (List<String> list : lists) {
            if (list.size() > num) {
                // 如果list的元素数量多于num，则从末尾删除多余的元素
                list.subList(num, list.size()).clear();
            } else if (list.size() < num) {
                // 如果list的元素数量少于num，则在末尾增加空字符串
                while (list.size() < num) {
                    list.add("");
                }
            }
        }

    }
}
